<template>
  <el-upload
    ref="uploadRef"
    :action="url"
    :on-change="changeFile"
    :headers="myHeaders"
    :data="uploadData"
    :on-success="handleSuccess"
    :show-file-list="false"
    :multiple="false"
    accept=".xlsx, .xlsx"
    style="display: inline;margin-left: 8px;margin-right: 8px;"
    :on-progress="progress"
    :disabled="disable"
    :on-error="backError"
  >
    <template #trigger>
      <el-button plain size="small" :loading="backStatus" :disabled="disable">
        <el-icon><Upload /></el-icon>
        {{ msg }}
      </el-button>
    </template>
  </el-upload>
</template>

<script setup lang="ts" name="slUploadButton">
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { Upload } from '@element-plus/icons-vue'
import { getCorpId, getDomainId, getToken, getUsername, getTokenName } from '@/utils/auth'
import Cookies from 'js-cookie'

interface Props {
  baseurl: string
  flag?: number
  uploadData?: Record<string, any>
}

const props = withDefaults(defineProps<Props>(), {
  flag: 0,
  uploadData: () => ({})
})

const emit = defineEmits<{
  (e: 'changefile'): void
  (e: 'onsuccess', res: any): void
}>()

const { t } = useI18n()
const uploadRef = ref()
const url = ref('')
const msg = ref('')
const disable = ref(false)
const backStatus = ref(false)

const myHeaders = ref({
  [getTokenName()]: getToken(),
  'x-user': getUsername(),
  'corp-id': '8e645c88-61fb-4b1f-bec4-ec371cfd271f',
  'x-corp': '8e645c88-61fb-4b1f-bec4-ec371cfd271f',
  'domain-id': getDomainId(),
  'x-domain': '09fc566c-f9fb-4aa7-8dc8-92155548efa3',
  'language': Cookies.get('language') === 'ch' ? 'ch' : 'us'
})

onMounted(() => {
  myHeaders.value[getTokenName()] = getToken()
  msg.value = t('message.components.upload')
  
  if (props.flag === -1) {
    url.value = props.baseurl
  } else if (props.flag === 0) {
    url.value = window.BASEURL.VUE_APP_TESLA_API + props.baseurl
  }
})

const changeFile = () => {
  console.log(props.flag)
  console.log(url.value)
  emit('changefile')
}

const handleSuccess = (res: any, file: any) => {
  emit('onsuccess', res)
  disable.value = false
  backStatus.value = false
  msg.value = t('message.components.uploadFile')
}

const progress = () => {
  backStatus.value = true
  disable.value = true
  msg.value = t('message.components.uploading')
}

const backError = () => {
  disable.value = false
  backStatus.value = false
}
</script>

<style>
</style>
